package main

import (
	"net/http"
	"strings"
	"html/template"
)

func serveRecipe(w http.ResponseWriter, r *http.Request) {
	code := strings.Split(r.RequestURI, "/")[2]
	
	for _, recipe := range *recp {
		if recipe.Code == code {
			if strings.HasPrefix(recipe.Description, "http://") {
				http.Redirect(w, r, localURL(recipe.Description), 302)
			} else {
				textRecipe(&recipe, w)
			}
			return;
		}
	}

	http.Error(w, "Recipe " + code + " not found.", 404)
}


func textRecipe(recipe *Recipe, w http.ResponseWriter) {
	var err error
	// load template
	t := template.New("")
	t, err = t.Parse(recipe_template)
	if err != nil {
		panic(err)
	}
	err = t.Execute(w, recipe)
	if err != nil {
		panic(err)
	}
}


const recipe_template = `
<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="UTF-8">
    <title>recp - {{ .Name }}</title>
    <style type="text/css">
	pre {
	 white-space: pre-wrap;       /* css-3 */
	 white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
	 white-space: -pre-wrap;      /* Opera 4-6 */
	 white-space: -o-pre-wrap;    /* Opera 7 */
	 word-wrap: break-word;       /* Internet Explorer 5.5+ */
	}
    </style>
  </head>
  <body>
    <h1>{{ .Name }}</h1>
    <hr>
    <p><a href="/">Voltar para o índice</a></p>
    <pre>
{{ .Description }}
    </pre>
  </body>
</html>
`

